package com.ld.ldliving.commodity.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.common.utils.PageUtils;
import com.ld.common.utils.Query;

import com.ld.ldliving.commodity.dao.CategoryDao;
import com.ld.ldliving.commodity.entity.CategoryEntity;
import com.ld.ldliving.commodity.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<CategoryEntity> page = this.page(
				new Query<CategoryEntity>().getPage(params),
				new QueryWrapper<CategoryEntity>()
		);

		return new PageUtils(page);
	}

	//返回所有分类及其子类(带有层级关系，即树形结构)
	//用到java8的流式计算 + 递归
	@Override
	public List<CategoryEntity> listWithTree() {
		//1.查出所有的分类数据
		List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
		//2.组装成层级树形结构，使用到java8的stream流式计算+递归操作
		//2.1过滤filter,返回一级分类
		//2.2 进行map映射操作，给每个分类添加子分类(递归操作)
		//2.3 排序，sorted操作
		//2.4将处理好的数据收集collect转换到集合中
		//3.返回
		List<CategoryEntity> categoryTree = categoryEntities.stream().filter(
				//过滤一级分类
				categoryEntity -> categoryEntity.getParentId() == 0
		).map(
				//给每个分类添加子分类(每一个过程会涉及到递归操作)
				categoryEntity -> {
					//给每个一级分类设置子分类
					categoryEntity.setChildrenCategories(getChildrenCategories(categoryEntity, categoryEntities));
					return categoryEntity;
				}).sorted((category1, category2) -> {
			//排序,按照升序排序
			return (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort());
		}).collect(Collectors.toList());
		return categoryTree;
	}


	//递归查询所有分类的子分类
	//该方法的任务是把root下的所有子分类的层级关系组织好并返回，有多少级就处理多少级
	//all就是所有的分类数据，即上个方法的categoryEntities
	private List<CategoryEntity> getChildrenCategories(CategoryEntity root, List<CategoryEntity> all) {
		//过滤
		List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
			return categoryEntity.getParentId() == root.getId();
		}).map(categoryEntity -> {
			//找到子分类，并设置递归
			categoryEntity.setChildrenCategories(getChildrenCategories(categoryEntity, all));
			return categoryEntity;
		}).sorted((category1, category2) -> {
			return (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort());
		}).collect(Collectors.toList());
		return children;
	}

}